<template>
    <div>
        <el-button type="primary" @click="showAddDialog">添加人员</el-button>
        <el-table :data="employees" style="width: 100%">
            <el-table-column prop="employeeNumber" label="工号"></el-table-column>
            <el-table-column prop="name" label="姓名" ></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column prop="employeeDepartment" label="部门"></el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <!-- 如果部门为“超级管理员”，禁用所有操作 -->
                    <div v-if="scope.row.employeeDepartment === '超级管理员'" class="disabled-row">
                        <el-button disabled>编辑</el-button>
                        <el-button type="danger" disabled>删除</el-button>
                        <el-button type="info" disabled>禁用</el-button>
                    </div>
                    <div v-else>
                        <el-button @click="showEditDialog(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="deleteEmployee(scope.row.employeeNumber)">删除</el-button>
                        <!-- 禁用/启用按钮 -->
                        <el-button
                            :type="scope.row.employeeStatus === 1 ? 'info' : 'danger'"
                            @click="toggleStatus(scope.row)"

                        >

                            {{ scope.row.employeeStatus === 1 ? '禁用' : '启用' }}
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加人员对话框 -->
        <el-dialog title="添加人员" v-model="addDialogVisible">
            <el-form :model="newEmployee" label-width="120px">
                <el-form-item label="工号">
                    <el-input v-model="newEmployee.employeeNumber"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="newEmployee.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="newEmployee.phone"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="newEmployee.employeePassword"></el-input>
                </el-form-item>
<!--                <el-form-item label="部门" prop="employeeDepartment">-->
<!--                    <el-select v-model="newEmployee.employeeDepartment" placeholder="请选择部门">-->
<!--                        <el-option label="超级管理员" value="超级管理员"></el-option>-->
<!--                        <el-option label="学工处" value="学工处"></el-option>-->
<!--                        <el-option label="科创部" value="科创部"></el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->


                <el-form-item label="部门" prop="employeeDepartment">
                    <el-select v-model="newEmployee.employeeDepartment" placeholder="请选择部门">
                        <el-option
                            v-for="department in departments"
                            :key="department.id"
                            :label="department.name"
                            :value="department.name"
                        ></el-option>
                    </el-select>
                </el-form-item>


            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addEmployee">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑人员对话框 -->
        <el-dialog title="编辑人员" v-model="editDialogVisible">
            <el-form :model="selectedEmployee" label-width="120px">
                <el-form-item label="工号">
                    <el-input v-model="selectedEmployee.employeeNumber" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="selectedEmployee.name"></el-input>
                </el-form-item>


                <el-form-item label="手机号">
                    <el-input v-model="selectedEmployee.phone"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="employeeDepartment">
                    <el-select v-model="selectedEmployee.employeeDepartment" placeholder="请选择部门">
                        <el-option
                            v-for="department in departments"
                            :key="department.id"
                            :label="department.name"
                            :value="department.name"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateEmployee">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {ref, onMounted, onBeforeUnmount} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import service from "@/utils/request";

export default {
    setup() {
        const employees = ref([]);
        const addDialogVisible = ref(false);
        const editDialogVisible = ref(false);
        const newEmployee = ref({
            employeeNumber: '',
            name: '',
            phone: '',
            employeePassword: '',
            employeeDepartment: '',
            // position: ''
            // employeeStatus: 1 // 默认启用
        });


        const departments = ref([]); // 用于存储从后端获取的部门数据

        // 获取部门数据的方法
        const fetchDepartments = async () => {
            try {
                const response = await service.get('/role/listAll'); // 假设后端接口为 /role/listAll
                if (response.data.data && Array.isArray(response.data.data)) {
                    // 直接将后端返回的数据赋值给 departments
                    departments.value = response.data.data;
                    console.log('Fetched departments:', departments.value); // 检查数据
                } else {
                    console.error('Invalid department data format:', response.data);
                }
            } catch (error) {
                console.error('Failed to fetch departments:', error);
            }
        };




        const selectedEmployee = ref({});
        //查询到员工数据之后再进行渲染映射
        const fetchEmployees = async () => {
            try {
                const response = await service.get('/admin/employee/list');
                employees.value = response.data; // 直接将响应数据赋值给 employees
            } catch (error) {
                console.error('Error fetching employees:', error);
            }
        };

        const toggleStatus = async (employee) => {
            try {
                const newStatus = employee.employeeStatus === 0 ? 1 : 0; // 1 表示启用，0 表示禁用
                await service.put(`/admin/employee/updateStatus/${employee.employeeNumber}/${newStatus}`);
                employee.employeeStatus = newStatus; // 更新前端状态
                ElMessage.success(`用户已${newStatus === 1 ? '启用' : '禁用'}`);
            } catch (error) {
                console.error('Error updating employee status:', error);
                ElMessage.error('更新用户状态失败');
            }
        };

        const showAddDialog = () => {
            console.log('showAddDialog called');
            addDialogVisible.value = true;
        };

        const showEditDialog = (employee) => {
            console.log('showEditDialog called', employee);
            selectedEmployee.value = { ...employee };
            editDialogVisible.value = true;
        };

        const addEmployee = async () => {
            try {
                await service.post('/admin/employee/add', newEmployee.value);
                await fetchEmployees();
                addDialogVisible.value = false;
                newEmployee.value = {
                    employeeNumber: '',
                    name: '',
                    phone: '',
                    employeePassword: '',
                    employeeDepartment: '',
                    employeeStatus: 1 // 默认启用
                };
            } catch (error) {
                console.error('Error adding employee:', error);
            }
        };

        const updateEmployee = async () => {
            try {
                // 使用工号更新员工信息
                await service.put(`/admin/employee/update`, selectedEmployee.value);
                await fetchEmployees();
                editDialogVisible.value = false;
                ElMessage.success('员工信息更新成功');
            } catch (error) {
                console.error('Error updating employee:', error);
                ElMessage.error('员工信息更新失败');
            }
        };

        const deleteEmployee = async (employeeNumber) => {
            try {
                await ElMessageBox.confirm('确定删除该人员吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                // 使用工号删除员工
                await service.delete(`/admin/employee/delete/${employeeNumber}`);
                await fetchEmployees();
            } catch (error) {
                console.error('Error deleting employee:', error);
            }
        };

        let timer = null;
// 在组件挂载时启动定时器
        onMounted(() => {
            timer = setInterval(() => {
                // 定时器逻辑
            }, 1000);
        });

// 在组件销毁前清理定时器
        onBeforeUnmount(() => {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        });
        onMounted(() => {
            fetchEmployees();
            fetchDepartments();

        });

        return {
            employees,
            addDialogVisible,
            editDialogVisible,
            newEmployee,
            selectedEmployee,
            departments,
            fetchEmployees,
            showAddDialog,
            showEditDialog,
            addEmployee,
            updateEmployee,
            deleteEmployee,
            toggleStatus
        };
    }
};
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}

/* 禁用行的样式 */
.disabled-row {
    opacity: 0.5; /* 使行变暗 */
    pointer-events: none; /* 禁用所有操作 */
}
</style>
